/*
 * File Name: LogUtils.java 
 * History:
 * Created by mwqi on 2014-4-4
 */
package com.yz.jdd.base.utils;

import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;


import com.yz.jdd.BuildConfig;

import java.io.File;
import java.io.FileWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 日志输出控制类 (Description)
 *
 * @author mwqi
 */
public class LogUtils {
    /**
     * 日志输出级别NONE
     */
    public static final int LEVEL_NONE = 0;
    /**
     * 日志输出级别V
     */
    public static final int LEVEL_VERBOSE = 1;
    /**
     * 日志输出级别D
     */
    public static final int LEVEL_DEBUG = 2;
    /**
     * 日志输出级别I
     */
    public static final int LEVEL_INFO = 3;
    /**
     * 日志输出级别W
     */
    public static final int LEVEL_WARN = 4;
    /**
     * 日志输出级别E
     */
    public static final int LEVEL_ERROR = 5;

    /**
     * 日志输出时的TAG
     */
    private static String mTag = BaseConfigs.M_TAG;
    /**
     * 是否允许输出log
     */
    private static int mDebuggable = LEVEL_ERROR;

    /**
     * 用于记时的变量
     */
    private static long mTimestamp = 0;
    /**
     * 写文件的锁对象
     */
    private static final Object mLogLock = new Object();

    /**
     * 以级别为 d 的形式输出LOG
     */
    public static void v(String msg) {
        if (BuildConfig.LOG_DEBUG && mDebuggable >= LEVEL_VERBOSE) {
            Log.v(mTag, msg);
        }

    }

    /**
     * 以级别为 d 的形式输出LOG
     */
    public static void d(String msg) {
        if (BuildConfig.LOG_DEBUG &&mDebuggable >= LEVEL_DEBUG) {
            Log.d(mTag, msg);
        }
    }

    /**
     * 以级别为 i 的形式输出LOG
     */
    public static void i(String msg) {
        if (BuildConfig.LOG_DEBUG &&mDebuggable >= LEVEL_INFO) {
            Log.i(mTag, msg);
        }
    }
    /**
     * 以级别为 i 的形式输出LOG
     * 打印输出结果过长使用
     */
    private static int LOG_MAXLENGTH = 2000;
    public static void iLong(String msg) {
        if (BuildConfig.LOG_DEBUG &&mDebuggable >= LEVEL_INFO) {
//            Log.i(mTag, msg);
                int strLength = msg.length();
                int start = 0;
                int end = LOG_MAXLENGTH;
                for (int i = 0; i < 100; i++) {
                    if (strLength > end) {
                        Log.i(mTag + i, msg.substring(start, end));
                        start = end;
                        end = end + LOG_MAXLENGTH;
                    } else {
                        Log.i(mTag + i, msg.substring(start, strLength));
                        break;
                    }
                }

        }

    }

    /**
     * 以级别为 w 的形式输出LOG
     */
    public static void w(String msg) {
        if (BuildConfig.LOG_DEBUG &&mDebuggable >= LEVEL_WARN) {
            Log.w(mTag, msg);
        }
    }

    /**
     * 以级别为 w 的形式输出Throwable
     */
    public static void w(Throwable tr) {
        if (BuildConfig.LOG_DEBUG &&mDebuggable >= LEVEL_WARN) {
            Log.w(mTag, "", tr);
        }
    }

    /**
     * 以级别为 w 的形式输出LOG信息和Throwable
     */
    public static void w(String msg, Throwable tr) {
        if (BuildConfig.LOG_DEBUG &&mDebuggable >= LEVEL_WARN && null != msg) {
            Log.w(mTag, msg, tr);
        }
    }

    /**
     * 以级别为 e 的形式输出LOG
     */
    public static void e(String msg) {
        if (BuildConfig.LOG_DEBUG &&mDebuggable >= LEVEL_ERROR) {
            Log.e(mTag, msg);
        }
    }

    /**
     * 以级别为 e 的形式输出Throwable
     */
    public static void e(Throwable tr) {
        if (BuildConfig.LOG_DEBUG &&mDebuggable >= LEVEL_ERROR) {
            Log.e(mTag, "", tr);
        }
    }

    /**
     * 以级别为 e 的形式输出LOG信息和Throwable
     */
    public static void e(String msg, Throwable tr) {
        if (BuildConfig.LOG_DEBUG &&mDebuggable >= LEVEL_ERROR && null != msg) {
            Log.e(mTag, msg, tr);
        }
    }

    /**
     * 把Log存储到文件中
     *
     * @param log  需要存储的日志
     * @param path 存储路径
     */
    public static void log2File(String log, String path) {
        File file = new File(path);
        if (file != null && file.exists() && file.isDirectory()) {
            Date dt = new Date();
            SimpleDateFormat matter1 = new SimpleDateFormat("yyyy-MM-dd");
            String filePath = path + matter1.format(dt) + ".txt";
            log2File(log, filePath, true);
        } else {
            log2File(log, path, true);
        }

    }

    public static void log2File(String log, String path, boolean append) {
        synchronized (mLogLock) {
            FileUtils.writeFile(log + "\r\n", path, append);
        }
    }

    /**
     * 以级别为 e 的形式输出msg信息,附带时间戳，用于输出一个时间段起始点
     *
     * @param msg 需要输出的msg
     */
    public static void msgStartTime(String msg) {
        mTimestamp = System.currentTimeMillis();
        if (!TextUtils.isEmpty(msg)) {
            e("[Started：" + mTimestamp + "]" + msg);
        }
    }

    /**
     * 以级别为 e 的形式输出msg信息,附带时间戳，用于输出一个时间段结束点* @param msg 需要输出的msg
     */
    public static void elapsed(String msg) {
        long currentTime = System.currentTimeMillis();
        long elapsedTime = currentTime - mTimestamp;
        mTimestamp = currentTime;
        e("[Elapsed：" + elapsedTime + "]" + msg);
    }

    public static <T> void printList(List<T> list) {
        if (list == null || list.size() < 1) {
            return;
        }
        int size = list.size();
        i("---begin---");
        for (int i = 0; i < size; i++) {
            i(i + ":" + list.get(i).toString());
        }
        i("---end---");
    }

    public static <T> void printArray(T[] array) {
        if (array == null || array.length < 1) {
            return;
        }
        int length = array.length;
        i("---begin---");
        for (int i = 0; i < length; i++) {
            i(i + ":" + array[i].toString());
        }
        i("---end---");
    }

    /**
     * 日志输出
     *
     * @param nameString
     * @param messageString
     */
    public static void Log(String nameString, Object messageString) {
        if (BaseConfigs.DEBUG) {
            if (nameString == null) {
                nameString = "undefined";
            }
           // LogToSdCard(nameString, messageString);
            if (nameString.contains("Exception")) {
                Log.e(nameString, messageString + "");
            } else {
                String result = messageString + "";
                while (result != null) {
                    if (result.length() > 2048) {
                        Log.v(nameString,
                                result.substring(0, 2048));
                        result = result.substring(2048);
                    } else {
                        Log.v(nameString, result);
                        result = null;
                    }
                }
            }
        }
    }

    public static void LogToSdCard(String nameString, Object messageString) {
        if (BaseConfigs.DEBUG
                && Environment.MEDIA_MOUNTED.equals(Environment
                .getExternalStorageState())) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (nameString == null) {
                nameString = "undefined";
            }
            SimpleDateFormat fomat = new SimpleDateFormat("yyyy-MM-dd");
            String filename = fomat.format(new Date());
            File f = null;
            try {
                FileUtils.createExternalFilesDir(
                        new StringBuffer().append(BaseConfigs.filePathRoot + "/logs"));
                f = new File(BaseConfigs.LOG_LOCATION, filename + ".txt");
                if (!f.exists()) {
                    f.createNewFile();
                }
                FileWriter fw = new FileWriter(f, true);
                String pageString = "TAG:" + nameString + "time:"
                        + sdf.format(new Date()) + messageString + "." + "\n";
                fw.write(pageString);
                fw.flush();
                fw.close();
            } catch (OutOfMemoryError ignored) {
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
